package com.jingyuan.biz.manager;

import com.jingyuan.biz.event.EventManager;
import com.jingyuan.biz.event.VoteEvent;
import com.jingyuan.common.entity.EventType;
import com.jingyuan.common.entity.ServerMessage;
import com.jingyuan.common.entity.packet.ServerMessageType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 选举过程管理器
 */
@Service
public class VoteProcessManager {
    @Resource
    private EventManager eventManager;

    @Resource
    private JNodeManager nodeManager;
    private AtomicBoolean isStartVoting=new AtomicBoolean(false);

    public AtomicBoolean getIsStartVoting() {
        return isStartVoting;
    }

    public void setIsStartVoting(AtomicBoolean isStartVoting) {
        this.isStartVoting = isStartVoting;
    }

    /**
     * 开始选举
     */
    public void startVoting(){
        //如果发现主机列表为空就无需选举了
        List<JNode> nodeList=nodeManager.getHostNode();

        if(nodeList.isEmpty()){
            return;
        }

        if(nodeList.size()==1){
            JNode node=nodeList.get(0);
            VoteEvent voteEvent=new VoteEvent();
            voteEvent.setPhase(VoteEvent.VOTE_END);
            voteEvent.setAddress(node.getAddress());
            voteEvent.setPort(node.getPort());
            eventManager.dispatch(voteEvent);
            return;
        }

        if(isStartVoting.compareAndSet(false,true)){
            VoteEvent voteEvent=new VoteEvent();
            voteEvent.setPhase(VoteEvent.VOTE_START);
            eventManager.dispatch(voteEvent);
        }
        //10秒后结束选举阶段
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10000);
                    endVoting();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void endVoting(){
        if(isStartVoting.compareAndSet(true,false)){
            JNode masterNode=null;
            for (JNode node:nodeManager.getHostNode()){
                if(masterNode==null){
                    masterNode=node;
                }else{
                    if(masterNode.getVoteValue()>node.getVoteValue()){
                        masterNode=node;
                    }
                }
            }
            VoteEvent voteEvent=new VoteEvent();
            voteEvent.setPhase(VoteEvent.VOTE_END);
            voteEvent.setAddress(masterNode.getAddress());
            voteEvent.setPort(masterNode.getPort());
            eventManager.dispatch(voteEvent);
        }
    }
}
